package com.hzqy.web.ac.epg;


import com.hzqy.commons.utils.ExcelUtil;
import com.hzqy.commons.utils.FileType;
import com.hzqy.web.vo.AcWinningVo;
import com.hzqy.service.epg.AcLotteryService;

import com.hzqy.web.vo.epg.AcTicketNumVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hzqy.commons.utils.ExcelUtil.MyEntry;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/acLottery")
public class AcLotteryAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	private static final String[] allowedFileType = new String[]{"png", "jpg", "gif", "zip", "jar", "tar", "docx", "doc", "xlsx", "xls", "flv", "mp4", "mp3", "mpg", "avi", "mov", "wmv"};
    @Resource
	private AcLotteryService serviceAction;
    @RequestMapping("/acLotterySelectAll")
	@ResponseBody
	public Object acLotterySelect(AcWinningVo alv,int page,int rows){
		Map<String,Object> LotteryListMap = new HashMap<String, Object>();
		LotteryListMap= serviceAction.selectAc(alv,page, rows);
		return LotteryListMap;
	}
	@RequestMapping("/acLotteryExcel")
	@ResponseBody
	public void acLotteryExcel(AcWinningVo infoVo, HttpSession session, int page, int rows, HttpServletResponse response) throws IOException {
		Map<String,Object> ListMap = new HashMap<String, Object>();
    	ListMap = serviceAction.selectAc(infoVo,page,rows);
		List<AcWinningVo> data=(List<AcWinningVo>)ListMap.get("rows");
		//导出解码
		Decoder decoder = Base64.getDecoder();
        for (int i = 0; i < data.size(); i++) {
        	try {
        		//手机号码
        		String phones = data.get(i).getF_awl_userphone();
        		if(isBase64(phones)){
        			byte[] bytes = decoder.decode(phones);
        			String phoneEnd = new String(bytes, "UTF-8");
        			data.get(i).setF_awl_userphone(phoneEnd);
        		}
        		String username = data.get(i).getF_awl_username();
    			if(isBase64(username)){
    				byte[] usernameByte = decoder.decode(username);
        			String usernameEnd = new String(usernameByte, "UTF-8");
    				data.get(i).setF_awl_username(usernameEnd);
    			}
    			String useraddress = data.get(i).getF_awl_useraddress();
    			if(isBase64(useraddress)){
    				byte[] useraddressByte = decoder.decode(useraddress);
        			String useraddressEnd = new String(useraddressByte, "UTF-8");
    				data.get(i).setF_awl_useraddress(useraddressEnd);
    			}
	        } catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		List<MyEntry<String, String>> excelHeader=new ArrayList<MyEntry<String, String>>();
		excelHeader.add(new MyEntry<String,String>("f_awl_id","ID"));
		excelHeader.add(new MyEntry<String,String>("f_awl_serverid","IPTV账号"));
		excelHeader.add(new MyEntry<String,String>("f_awl_userphone","中奖手机号"));
		excelHeader.add(new MyEntry<String,String>("f_awl_username","姓名"));
		excelHeader.add(new MyEntry<String,String>("f_awl_useraddress","地址"));
		excelHeader.add(new MyEntry<String,String>("f_awl_nickname","微信昵称"));
		excelHeader.add(new MyEntry<String,String>("f_awl_prizeid","奖品ID"));
		excelHeader.add(new MyEntry<String,String>("f_awl_prizename","奖品名称"));
		excelHeader.add(new MyEntry<String,String>("f_awl_activityid","活动ID"));
		excelHeader.add(new MyEntry<String,String>("f_awl_date","中奖日期"));
		excelHeader.add(new MyEntry<String,String>("f_ui_resolution","用户分组"));
		boolean flag= ExcelUtil.generateExcel(data, excelHeader, response);
	}
	public Boolean isBase64(String prizename){
		if("null".equals(prizename) || "".equals(prizename) || prizename==null){
			return false;
		}
		Decoder decoder = Base64.getDecoder();
		Encoder encoder = Base64.getEncoder();
		String decode = "";
		String encode = "";
		try {
			byte[] bytes = decoder.decode(prizename);
			decode = new String(bytes, "UTF-8");
			encode = encoder.encodeToString(decode.getBytes());
		} catch (Exception e1) {
			//LOG.error("isBase64-e:"+e1.getMessage());
			return false;
		}
		if(encode.equals(prizename)){//已加密数据
			return true;
		}else{//未加密数据
			return false;
		}
	}
/*	@RequestMapping("/importLotteryList")
	@ResponseBody
	public Object insertLottery(@RequestParam(value = "uploadify") MultipartFile file , HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		if (FileType.checkFileType(file.getInputStream(), allowedFileType)) {
			int successCount = 0;
			StringBuffer str = new StringBuffer();
			InputStream is = null;
			try {
				LOG.debug("批量导入Ticket开始");
				is = file.getInputStream();
				List<Map<String, Object>> list = ExcelUtil.parseExcel(is, ExcelUtil.ALLOWED_EMPTY_MODE, new String[]{});
				LOG.debug("解析excel完成, 开始循环入库" + list.size());
				for (int i = 0; i < list.size(); i++) {
					AcWinningVo winning = new AcWinningVo();
					Map<String, Object> map = list.get(i);
					winning.setF_awl_serverid(map.get("IPTV账号").toString());
					String phone = "";
					//导入转码
					Encoder encoder = Base64.getEncoder();
					if (map.get("中奖手机号") != null) {
						phone = encoder.encodeToString(map.get("中奖手机号").toString().getBytes());
					}
					winning.setF_awl_userphone(phone);
					winning.setF_awl_date(map.get("中奖日期").toString());
					String prizename = "";
					if (map.get("奖品名称") != null) {//
						String name = map.get("奖品名称").toString();
						if (name.indexOf("<>") != -1) {
							prizename = encoder.encodeToString(name.getBytes());
						} else {
							prizename = name;
						}
					}
					winning.setF_awl_prizename(prizename);
					String username = "";
					if (map.get("用户名称") != null) {
						String name = map.get("用户名称").toString();
						username = encoder.encodeToString(name.getBytes());
					}
					winning.setF_awl_username(username);
					String addressname = "";
					if (map.get("用户名称") != null) {
						String name = map.get("用户名称").toString();
						addressname = encoder.encodeToString(name.getBytes());
					}
					winning.setF_awl_useraddress(addressname);
					if (map.get("奖品ID") != null) {
						winning.setF_awl_prizeid(map.get("奖品ID").toString());
					}
					if (map.get("活动ID") != null) {
						winning.setF_awl_activityid(map.get("活动ID").toString());
					}
					if (map.get("用户分组") != null) {
						Integer resolution = 0;
						if ("高清".equals(map.get("用户分组").toString())) {
							resolution = 2;
						} else if ("标清".equals(map.get("用户分组").toString())) {
							resolution = 1;
						}
						winning.setF_ui_resolution(resolution);
					}
					if (map.get("类型") != null) {
						winning.setF_awl_type(map.get("类型").toString());
					}
					boolean success = false;
					Map<String, Object> resultMap = serviceAction.insertWinningService(winning);
					success = (Boolean) resultMap.get("success");
					successCount += (success ? 1 : 0);
				}
				LOG.debug("批量完成" + successCount);
				successCount = successCount;
				str.append("一共").append(list.size()).append("条数据").append("批量导入完成,").append(successCount).append("条数据成功，").append(list.size() - successCount).append("条失败");
			} catch (Exception e) {
				LOG.error("", e);
				//str.append("批量导入过程有异常!" +"成功条数"+successCount+ e.getMessage());
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
			return str.toString();
		} else {
			return "";
		}
	}*/
	//根据id查询
	@RequestMapping("/selectAcWinningById")
	@ResponseBody
	public Object selectAcWinningById(int f_awl_id){
		return serviceAction.selectAcWinningById(f_awl_id);
		
		
	}
	//根据id删除
	@RequestMapping("/deleteAcWinning")
	@ResponseBody
	public Object deleteAcWinning(int f_awl_id){
		Map<String,Object> ListMap = serviceAction.deleteAcWinning(f_awl_id);
		return ListMap;
	}
	//根据id修改
	@RequestMapping("/updateAcWinning")
	@ResponseBody
	public Object updateAcWinning(AcWinningVo awv){
		Map<String,Object> ListMap = serviceAction.updateAcWinning(awv);
		return ListMap;
	}

}
